package com.donleo.security.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.donleo.security.common.CommonResult;
import com.donleo.security.mapper.UserMapper;
import com.donleo.security.model.Permission;
import com.donleo.security.model.User;
import com.donleo.security.service.UserService;
import com.donleo.security.utils.JwtTokenUtil;
import com.donleo.security.vo.LoginParams;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashSet;
import java.util.List;

/**
 * @author liangd
 * @since 2021-01-15 17:33
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User getUserByCode(String code) {
        List<User> users = userMapper.getUserByCode(code);
        Assert.isTrue(users.size() == 1, "您输入的账户不存在，或者有多个相同的账户");
        return users.get(0);
    }

    @Override
    public List<Permission> getPermissionsByUserCode(String userCode) {
        return userMapper.getPermissionsByUserCode(userCode);
    }

    @Override
    public String login(LoginParams loginParams) {
        String code = loginParams.getCode();
        Assert.notNull(code, "账号必须不能为空");
        String password = loginParams.getPassword();
        Assert.notNull(password, "密码必须不能为空");
        User userByCode = getUserByCode(code);
        //判断用户输入的密码与数据库中查出来的密码是否相等
        boolean matches = passwordEncoder.matches(password, userByCode.getPassword());
        if(matches){
            //查询用户权限
            List<Permission> permissionsByUserCode = getPermissionsByUserCode(userByCode.getCode());
            //去重
            HashSet<Permission> permissions = new HashSet<>(permissionsByUserCode);
            //赋值
            userByCode.setAuthorities(permissions);
            //生成token
            return jwtTokenUtil.generateToken(userByCode);
        }
        return null;
    }

    @Override
    public CommonResult checkAuth(String userCode, String uri) {
        List<Permission> permissions = getPermissionsByUserCode(userCode);
        //只要有一个路径匹配就返回true
        boolean b = permissions.stream().anyMatch(permission -> StringUtils.equals(permission.getUri(), uri));
        if (b){
            return CommonResult.success(true);
        }
        return CommonResult.failed();
    }
}
